package com.ceba.test.task.subtask;

import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.base.enums.QrFileUploadFlagEnum;
import com.ceba.test.modules.admin.helper.QRCodeHelper;
import com.ceba.test.modules.sign.logicService.SignLogicService;
import com.ceba.test.modules.statistic.entity.ReportSign;
import configs.context.SpringBeans;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by liguangyao on 4/13/2020.
 */
@DisallowConcurrentExecution
public class QrFileUploadTask implements Job {

    private static Logger logger = LoggerFactory.getLogger(QrFileUploadTask.class);

    private static SignLogicService signLogicService = SpringBeans.getSignLogicService("signLogicService");

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        doUploadQrFile();
    }

    public static void doUploadQrFile() {
        if(("true".equals(CebaConfig.QR_PDF_NEED_UPLOAD) || "async".equals(CebaConfig.QR_PDF_NEED_UPLOAD)) && "true".equals(CebaConfig.QRCODE)) {
            List<ReportSign> signedReports = null;
            try {
                signedReports = signLogicService.getReportSign(QrFileUploadFlagEnum.UPLOAD_FAILURE);
                logger.info("数据库查询二维码文件结束");
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("查询二维码文件错误:" + e.getMessage(), e);
            }

            if (null != signedReports && !signedReports.isEmpty()) {
                logger.info("开始上传qr文件");

                for (int cnt=0; cnt<300 && cnt < signedReports.size(); ++cnt) {
                    ReportSign oneReport = signedReports.get(cnt);
                    try {
                        if (QRCodeHelper.sendQRPdfToServer(oneReport.getFileId(), oneReport.getFilePath())) {
                            signLogicService.updateReportSign(oneReport.getId(), QrFileUploadFlagEnum.UPLOAD_SUCCESS);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("上传二维码文件错误:" + e.getMessage(), e);
                    }
                }
            }

            logger.info("结束上传qr文件");
        }
    }
}
